package com.wmx.controller;

import com.wmx.common.CardJUntils;
import com.wmx.common.ExcelUtil;
import com.wmx.common.HttpClientTools;
import com.wmx.entity.DataEntity;
import com.wmx.service.ExcelService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

/**********************************
 * @author wmx
 * @date 2019/10/24 13:53
 * @description:
 * @version 1.0
 ************************************/
@RestController
@RequestMapping("/sys/")
public class ExcelController {
    @Autowired
    private ExcelService excelService;


    @PostMapping(value = "upload")
    public String uploadExcel(@RequestParam("file") MultipartFile file) {
        System.out.printf("============================");
        if (file.isEmpty()) {
            return "文件不能为空";
        }
        try {
            InputStream inputStream = file.getInputStream();
            List<List<Object>> list = excelService.getBankListByExcel(inputStream, file.getOriginalFilename());
            List<List<Object>> removeRepetitionId = list.stream().collect(
                    collectingAndThen(
                            toCollection(() -> new TreeSet<>(Comparator.comparing(v -> v.get(0).toString()))), ArrayList::new)
            );
            inputStream.close();
            List<DataEntity> dataEntities = new ArrayList<>();
            int count = 0;
            for (List<Object> obj : removeRepetitionId) {
                System.out.println(obj);
                count += 1;
                System.out.println("===========开始爬取第============:::::"+  count);
                DataEntity dataEntity = new DataEntity();
                dataEntity.setName(obj.get(0).toString());
                dataEntity.setIdCard(obj.get(4).toString());
                //dataEntity.setPwd(obj.get(4).toString());
                dataEntity.setPwd("123456");
                dataEntity.setPhone("无");
                dataEntity.setIntegral("无");
                dataEntity.setRemark("无");

                if (obj.size() > 7) {
                    dataEntity.setPhone((obj.get(5).toString() == null || obj.get(5).toString().equals("")) ? obj.get(6).toString() : obj.get(5).toString());
                }
                if (obj.get(1).toString() == null || obj.get(1).toString() == "") {
                    dataEntity.setValid("否");
                    dataEntity.setIdCard("无效");
                    dataEntity.setAge("无效");
                    dataEntity.setSex("无效");
                } else {

                    String idCard = obj.get(4).toString();
                    if (idCard.length() == 18) {
                        Map<String, Object> stringObjectMap = CardJUntils.identityCard18(idCard);
                        dataEntity.setAge(stringObjectMap.get("age").toString());
                        dataEntity.setSex(stringObjectMap.get("sex").toString());
                    } else {

                        dataEntity.setIdCard(dataEntity.getIdCard() + "无效");
                        dataEntity.setAge("无效");
                        dataEntity.setSex("无效");
                    }


                }
                if (dataEntity.getIdCard() != null && dataEntity.getPwd() != null && !dataEntity.getIdCard().equals(dataEntity.getIdCard() + "无效")) {
                    HashMap<String, Object> hashMap = new HashMap<>();

                    hashMap.put("user", dataEntity.getIdCard());
                    hashMap.put("pwd", dataEntity.getPwd());
                    TimeUnit.SECONDS.sleep(5);
                    String url = "http://127.0.0.1:5000/collect?user="+dataEntity.getIdCard()+"&pwd="+dataEntity.getPwd();
                    String s = HttpClientTools.doGet(url);
                    //String s = "ERROR";
                    System.out.println("收集信息返回结果=============" + s);
                    if (!"ERROR".equals(s)) {
                        JSONObject jsonObject = JSONObject.fromObject(s);
                        String code = jsonObject.getString("code");
                        if (code != null && "200".equals(code)) {
                            JSONObject body = jsonObject.getJSONObject("body");
                            String tel = body.getString("tel");
                            String integral = body.getString("integral");
                            String date = body.getString("date");
                            dataEntity.setPhone(tel);
                            dataEntity.setIntegral(integral);
                            dataEntity.setRemark(date);
                            dataEntity.setValid("是");
                        } else {
                            dataEntity.setValid("否");
                            dataEntity.setPwd(dataEntity.getPwd() + "(密码错误)");

                        }
                    } else {
                        dataEntity.setValid("否");
                        dataEntity.setPwd(dataEntity.getPwd() + "(密码错误)");
                    }

                }
                System.out.println("=============" + dataEntity.toString());
                dataEntities.add(dataEntity);
            }


            LinkedHashMap<String, String> stringStringLinkedHashMap = new LinkedHashMap<>();
            stringStringLinkedHashMap.put("name", "姓名");
            stringStringLinkedHashMap.put("idCard", "省份证号码");
            stringStringLinkedHashMap.put("pwd", "密码");
            stringStringLinkedHashMap.put("phone", "联系方式");
            stringStringLinkedHashMap.put("sex", "性别");
            stringStringLinkedHashMap.put("age", "年龄");
            stringStringLinkedHashMap.put("integral", "积分");
            stringStringLinkedHashMap.put("valid", "是否有效");
            stringStringLinkedHashMap.put("remark", "备注");
            String sheetName = "新能社区志愿者信息统计表";
            UUID uuid = UUID.randomUUID();
            String filedisplay = "新能社区志愿者信息统计表" + ".xls";
            OutputStream out = new FileOutputStream("D:\\" + filedisplay);
            // 设置监听
            ExcelUtil.listToExcel(dataEntities, stringStringLinkedHashMap, sheetName, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传成功";
    }

}
